package org.aeon.server.handler;

import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.aeon.message.PingMessage;
import org.aeon.message.PongMessage;
import org.aeon.service.Session;
import org.aeon.service.factory.SessionFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: MissingAeon
 * @date: 2024/1/29 15:12
 * @description: 检测信号检测处理程序
 */
@Slf4j
@ChannelHandler.Sharable
public class HeartbeatDetectionHandler extends ChannelDuplexHandler {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof final IdleStateEvent event) {
            // 判断是否为读空闲
            if (event.state() == IdleState.READER_IDLE) {
                final Session session = SessionFactory.getSession();
                // 尝试获取离线计数
                AtomicInteger leaveCount = (AtomicInteger) session.getAttribute(ctx.channel(), "LeaveCount");
                if (leaveCount == null) {
                    // 没有离线计数且未创建直接断开
                    if (session.getUserId(ctx.channel()) == null) {
                        ctx.channel().close();
                        return;
                    } else {
                        // 添加离线计数
                        session.setAttribute(ctx.channel(), "LeaveCount", (leaveCount = new AtomicInteger(0)));
                    }
                } else leaveCount.incrementAndGet();
                // 超过规定时间断开连接
                if (leaveCount.get() > 5) ctx.channel().close();
            }
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof PingMessage) {
            // 回应
            ctx.writeAndFlush(new PongMessage());
            return;
        }
        super.channelRead(ctx, msg);
    }
}
